﻿/**
 * jQuery EasyUI 1.4
 * 
 * Copyright (c) 2009-2014 www.jeasyui.com. All rights reserved.
 * 
 * Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt To use it
 * on other terms please contact us at info@jeasyui.com
 * 填空题
 * question的结构
 * {
 * 	
 * }
 */
(function($) {
	itemChar = "A".charCodeAt();
	function deleteObject(array,id) {
		if(array && array instanceof Array){
			for (var i = 0, len = array.length; i < len; i++) {
				if (array[i] == id) {
					array.splice(i, 1);
					return;
				}
			}
		}
	};
	
	function create(target){
		var blanksQuestion = $.data(target, 'blanksQuestion');
		var opts = blanksQuestion.options;
		$(target).qtiBox($.extend({}, opts, {
			cls:"blanksQuestion"
		}));
		var qtiBox = $.data(target, 'qtiBox');
		var qtiBoxOpts = qtiBox.options;
		$(target).addClass(qtiBoxOpts.status);
		//如果试题，内容为空，这给出初始化数据。
		if(qtiBoxOpts.question==null){
			qtiBoxOpts.question={
					id:null,
					isNew:true,
					keywords:"关键字",
					context:"题干内容",
					categoryItemId:null,
					type:opts.type,
			};
			qtiBoxOpts.question.candidateAnswer=new Array();
		}else{
			if(qtiBoxOpts.question.candidateAnswer == undefined || qtiBoxOpts.question.candidateAnswer ==null){
				qtiBoxOpts.question.candidateAnswer=new Array();
			}
		}
		loadQuestion(target, qtiBoxOpts.question);
	};
	
	//加载一个新的实体
	function loadQuestion(target,question){
		if(!question){
			return;
		}
		var qtiBox = $.data(target, 'qtiBox');
		var qtiBoxOpts = qtiBox.options;
		//创建题干
		createQtiPprompt(target,question);
		//创建项
		var candidateAnswer=question.candidateAnswer;
		var olPanel=$("<ol class=\"plain block-listing solid choice-area\">");
		$(target).append(olPanel);
		for(var i=0;i<candidateAnswer.length;i++){
			var answer=candidateAnswer[i];
			createItem(olPanel,question,answer,i+1,false);
		}
		//创建虚拟键按钮
		var addOption=$("<div data-role=\"add-option\" data-edit=\"question\" class=\"add-option\"><span class=\"icon-add\"></span>添加填空</div>");
		
		$(target).append(addOption);
		addOption.bind("mousedown",function(){
			var blanksQuestion = $.data(target, 'blanksQuestion');
			var opts = blanksQuestion.options;
			var editor=opts.promptNicEditor;
			if(editor.selectedInstance){
				var selectElm=editor.selectedInstance.selElm();
				if($(selectElm).parents(".nicEdit-context").length>0){
					var answer={id:null,
							isNew:true,
							isCorrectAnswer:false,
							context:"",
							sortContext:String.fromCharCode(itemChar+candidateAnswer.length),
							optionAnswer:[""]
						};
					question.candidateAnswer.push(answer);
					createItem(olPanel,question,answer,candidateAnswer.length,true);
					editor.selectedInstance.execCommand("inserthtml","<input type='button' class='blanksQuestion_placeholder_inp' value='( )'/>");
					var inx=0;
					jQuery(editor.selectedInstance.elm).find(".blanksQuestion_placeholder_inp").each(function(){
						$(this).attr("inx",inx++);
					});
					var testBoxOpts=$(qtiBoxOpts.testBox).testBox("options");
					if(testBoxOpts){
						testBoxOpts.onCountBlanksAndLineMarks.call(target,question,"add");
					}
				}
				
			}else{
				var range = editor.nicInstances[0].selection.getRange();
				range.select();
				editor.selectedInstance.execCommand("inserthtml","<input type='button' value='( )' class='blanksQuestion_placeholder_inp'/>");
				$.messager.show({
					title:"消息提示",
					msg:"请您确认，你需要填空的位置",
					showType:"slide",
					timeout:2000,
					style:{
						right:'',
						top:document.body.scrollTop+document.documentElement.scrollTop,
						bottom:''
					}
				},"error");
			}
		});
	
		//创建一个题干
		function createQtiPprompt(panel,question){
			var blanksQuestion = $.data(target, 'blanksQuestion');
			var opts = blanksQuestion.options;
			opts.promptNicEditor = $.fn.nicEditor({fullPanel : true});
			opts.promptNicEditor.addEvent("key",function(editor,e){
				var notRemove=[];
				var idx=0;
				jQuery(editor.elm).find(".blanksQuestion_placeholder_inp").each(function(){
					notRemove.push($(this).attr("inx"));
					$(this).attr("inx",idx++);
				});
				for(var i=question.candidateAnswer.length-1;i>=0;i--){
					var isRemove=true;
					for(var n=0;n<notRemove.length;n++){
						if(i==notRemove[n]){
							isRemove=false;
							break;
						}
					}
					if(isRemove){
						var an=question.candidateAnswer[i];
						if(an.contextObj){
							var liItem=an.contextObj.parents(".fill-result-bar");
							if(liItem.length>0){
								deleteObject(question.candidateAnswer,an);
								liItem.remove();
								var inchar=0;
								olPanel.find("li.fill-result-bar").each(function(){
									var context=String.fromCharCode(itemChar+inchar++);
									$(this).find("label.real-label").html(context);
									var answer=$(this).data("answer");
									if(answer){
										answer.context=context;
									}else{
										answer={id:null,
											isNew:true,
											isCorrectAnswer:false,
											context:"",
											sortContext:String.fromCharCode(itemChar+candidateAnswer.length),
											optionAnswer:[""]
										};
										$(this).data("answer",answer);
										question.candidateAnswer.push(answer);
									}
								});
								//2015.11.30 添加以下的计算
								var testBoxOpts=$(qtiBoxOpts.testBox).testBox("options");
								if(testBoxOpts){
									testBoxOpts.onCountBlanksAndLineMarks.call(target,question,"remove");
								}
							}
						}
					}
				}
			});
			
			var container=opts.promptNicEditor.createEle("DIV").addClass("prompt qtiBox-prompt-container");
			$(target).append(container);
			$(container).css("position","relative");
			
			var context=opts.promptNicEditor.createEle("DIV").addClass("context qtiBox-prompt");
			context.appendTo(container);
			$(context).html(question.context);
			$(context).bind("mousedown",function(){
				if(qtiBoxOpts.status=="edit-answer"){
					return;
				}
				if(jQuery.trim($(context).html())=="题干内容"){
					$(context).html("");
				}
			});
			
			$(context).blur(function(){
				var str=$(context).html();
				if(jQuery.trim(str)==""){
					$(context).html("题干内容");
				}
			});
			var miniTlb=$("<div class=\"qtiBox-mini-tlb\"></div>");
			$(container).append(miniTlb);
			var aButton=$("<button type=\"button\" class=\"icon-font\"></button>");
			miniTlb.append(aButton);
			
			$(container).bind("mousedown",function(){
				if(qtiBoxOpts.status=="edit-answer"){
					return;
				}
				var containerTool=$(target).data("_containerTool");
				if(!containerTool){
					containerTool=opts.promptNicEditor.createEle("DIV").addClass("tool");
					$(containerTool).hide();
					containerTool.appendTo(container);
					opts.promptNicEditor.setPanel(containerTool);
					opts.promptNicEditor.addInstance(context);
					$(target).data("_containerTool",containerTool);
				
				}
				if(aButton.data("status-show")){
					if(containerTool){
						$(containerTool).show();
					}
				}
				aButton.show();
			});
			$(container).hover(function(){
			},function(){
				var containerTool=$(target).data("_containerTool");
				if(containerTool){
					$(containerTool).hide();
				}
				aButton.hide();
			});
			aButton.bind("mousedown",function(e){
				if(qtiBoxOpts.status!="edit-question"){
					return;
				}
				var status_show=aButton.data("status-show");
				var containerTool=$(target).data("_containerTool");
				if(!containerTool){
					containerTool=opts.promptNicEditor.createEle("DIV").addClass("tool");
					$(containerTool).hide();
					containerTool.appendTo(container);
					opts.promptNicEditor.setPanel(containerTool);
					opts.promptNicEditor.addInstance(context);
					$(target).data("_containerTool",containerTool);
				}
				if(status_show){
					aButton.data("status-show",false);
					$(containerTool).show();
				}else{
					aButton.data("status-show",true);
					$(containerTool).hide();
				}
			});
			if(qtiBoxOpts.status!="edit-question"){
				$(context).focus();
				aButton.show();
			}
			$(context).html(question.question);
			//设置当期的内容对象
			question.contextObj=$(context);
		}
		
		function createItem(olPanel,question,answer,index,isFocus){
			if (!answer) {
				return;
			}
			var qtiBox = $.data(target, 'qtiBox');
			var qtiBoxOpts = qtiBox.options;
			
			
			var liPan=$("<li class=\"fill-result-bar "+qtiBoxOpts.status+"\"></li>");
			
			olPanel.append(liPan);
			
			liPan.data("answer",answer);
			
			var container=$("<div class=\"container qtiBox-answer-container\"/>");
			liPan.append(container);
			
			
			$(container).css("position","relative");
			
			var item=$("<div class=\"qtiBox-item-box\"></div>");
			container.append(item);
			//填空序号
			var label=$("<label class=\"real-label\">"+answer.sortContext+"</label>");
			//初始化答案，
			item.append(label);
			var context=$("<div class=\"inp-box\"></div>");
			context.data("answer",answer);
			
			var text=$("<input class=\"inp label\" type=\"text\" placeholder=\"一个空可以有多个答案时,最多可输入10个答案\" disabled=\"\">");
			var textContext=$("<input class=\"inp context\" type=\"text\" value=\""+answer.optionAnswer[0]+"\" style=\"display:none\">");
			context.append(text);
			context.append(textContext);
			for(var anIndex=1;anIndex<answer.optionAnswer.length;anIndex++){
				context.append($("<input class=\"inp context\" value=\""+answer.optionAnswer[anIndex]+"\" type=\"text\" placeholder=\"新答案\" style=\"display:none\">"));
			}
			
			context.appendTo(item);
			answer.contextObj=textContext;
			
			var miniTlb=$("<div class=\"qtiBox-mini-tlb item-tlb\"></div>");
			//答案的删除操作
			var answerDelButton=$("<button type=\"button\" class=\"blanks-answer-del\"></button>").bind("click",function(){
				var inputs=$(this).parents("div.container").find(".inp-box>input");
				if(inputs.length>1){
					inputs[inputs.length-1].remove();
				}
			});
			miniTlb.append(answerDelButton);
			//答案的添加操作
			var answerAddButton=$("<button type=\"button\" class=\"blanks-answer-add\"></button>").bind("click",function(){
				var newText=$("<input class=\"inp context\" type=\"text\" placeholder=\"新答案\">");
				context.append(newText);
			});
			miniTlb.append(answerAddButton);
			
			container.append(miniTlb);
			var delButton=$("<button type=\"button\" class=\"icon-bin\"></button>");
			miniTlb.append(delButton);
			
			delButton.bind("mousedown",function(e){
				if(qtiBoxOpts.status!="edit-question"){
					return;
				}
				var blanksQuestion = $.data(target, 'blanksQuestion');
				var opts = blanksQuestion.options;
				
				var idx=0;
				olPanel.find("li.fill-result-bar").each(function(){
					if(answer==$(this).data("answer")){
						jQuery(opts.promptNicEditor.nicInstances[0].elm).find("input[inx="+idx+"]").remove();
					};
					idx++;
				});
				idx=0;
				//重置顺序
				jQuery(opts.promptNicEditor.nicInstances[0].elm).find(".blanksQuestion_placeholder_inp").each(function(){
					$(this).attr("inx",idx++);
				});
				deleteObject(question.candidateAnswer,answer);
				liPan.remove();
				var inchar=0;
				olPanel.find("li.fill-result-bar").each(function(){
					var context=String.fromCharCode(itemChar+inchar++);
					$(this).find("label.real-label").html(context);
					var answer=$(this).data("answer");
					if(answer){
						answer.context=context;
					}else{
						answer={id:null,
							isNew:true,
							isCorrectAnswer:false,
							context:"",
							sortContext:String.fromCharCode(itemChar+candidateAnswer.length),
							optionAnswer:[""]
						};
						$(this).data("answer",answer);
						question.candidateAnswer.push(answer);
					}
				});
				//2015.11.30 添加以下的计算
				var testBoxOpts=$(qtiBoxOpts.testBox).testBox("options");
				if(testBoxOpts){
					testBoxOpts.onCountBlanksAndLineMarks.call(target,question,"remove");
				}
			});
			if(isFocus && qtiBoxOpts.status!="edit-question"){
				$(context).focus();
				if (!liPan.hasClass('edit-active')){
					liPan.addClass('edit-active');
				}
				if (!$(context).hasClass('cke_focus')){
					$(context).addClass('cke_focus');
				}
			}
		}
	}
	
	$.fn.blanksQuestion = function(method, options) {
		if (typeof method == "string") {
			var methodBox =  $.fn.blanksQuestion.methods[method];
			if (methodBox){
				return methodBox(this, options);
			} else {
				return this.qtiBox(method, options);
			}
		}
		method = method || {};
		return this.each(function() {
			var blanksQuestion = $.data(this, "blanksQuestion");
			var opts;
			if (blanksQuestion) {
				opts = $.extend(blanksQuestion.options, method);
				blanksQuestion.isLoaded = false;
			} else {
				opts = $.extend({}, $.fn.blanksQuestion.defaults, $.fn.blanksQuestion.parseOptions(this), method);
				$(this).attr("title", "");
				blanksQuestion = $.data(this, "blanksQuestion", {
					options : opts,
					isLoaded : false
				});
			}
			create(this);
		});
	};
	$.fn.blanksQuestion.methods = {
		options : function(jq) {
			return $.data(jq[0], "blanksQuestion").options;
		},
		createContent:function(jq){
			return jq.each(function(){
				createContent(this);
			});
		},toJson:function(jq,question){
			return jq.each(function() {
				var opts=$.data(this, "blanksQuestion").options;
				return opts.questions;
			});
		}
	};
	$.fn.blanksQuestion.parseOptions = function(target) {
		return $.extend({}, $.fn.qtiBox.parseOptions(target));
	};
	
	$.fn.blanksQuestion.defaults = $.extend({}, $.fn.qtiBox.defaults, {
		questionButEvent:function(target){
			$(target).qtiBox("setStatusEdit");
			$(target).find(".inp-box").each(function(){
				var answer=$(this).data("answer");
				var i=0;
				$(this).find("input.label").show();
				$(this).find("input.context").each(function(){
					answer.optionAnswer[i++]=$(this).val();
				}).hide();
			});
		},
		clearAnswerCall:function(target){
			$(target).find(".inp-box").each(function(){
				var answer=$(this).data("answer");
				var i=0;
				$(this).find("input.label").show();
				$(this).find("input.context").each(function(){
					answer.optionAnswer[i++]=$(this).val();
				}).hide();
			});
		},
		responseButEvent:function(target){
			$(target).qtiBox("setStatusAnswer");
			$(target).find(".inp-box").each(function(){
				var answer=$(this).data("answer");
				var i=0;
				$(this).find("input.label").hide();
				$(this).find("input.context").each(function(){
					$(this).val(answer.optionAnswer[i++]);
				}).show();
			});
		},
		nicEditor:null,
		nicEditorPanel:null,
		instanceArray:null,
		contentCall:function(target){},
	});
})(jQuery);
